package yu.zhou.njupt.importdata.core.impl;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;

import au.com.bytecode.opencsv.CSVReader;
import yu.zhou.njupt.importdata.core.Importer;
import yu.zhou.njupt.importdata.entity.ImportResult;
import yu.zhou.njupt.importdata.entity.enumtype.CreateTable;
import yu.zhou.njupt.importdata.entity.enumtype.DoTruncate;
import yu.zhou.njupt.importdata.entity.enumtype.NewImport;
import yu.zhou.njupt.importdata.util.RegexUtil;

/** 
 * 用于导入csv文件，
 * 一个文件对应一张表，文件名为表名
**/
public class CsvImporter extends Importer{

    public CsvImporter(Connection conn, DoTruncate doTruncate, NewImport newImport, CreateTable createTable, int titleNum) throws Exception {
        super(conn, doTruncate, newImport, createTable, titleNum);
    }

    public ImportResult importData(File sourceFile,
            List<String> disableConsStrSet, List<String> enableConsStrSet, 
            List<String> disableIndexesStrSet, List<String> enableIndexesStrSet){
        int count = 0;
        int recordCount = 0;
        long elapsedTime = 0;
        String csvRow[] = null;
        String filename = null;
        String tableName = null;
        String sheetName = null;
        ImportResult importResult = null;
        PreparedStatement ps = null;
        CSVReader csvReader = null;
        
        try {
            Date startTime = new Date();
            DataInputStream dis = new DataInputStream(new FileInputStream(sourceFile));
            csvReader = new CSVReader(new InputStreamReader(dis, Charset.forName("GBK")));
            filename = sourceFile.getName();
            
            if (!hasDealt(filename, sheetName)) {
                tableName = RegexUtil.getValidName(filename).toUpperCase();
                
                columnIndexList = new ArrayList<Integer>();
                List<String> cellNameList = new ArrayList<String>();
                String[] csvTitle = csvReader.readNext();
                for (int i = 0; i < csvTitle.length; i++) {
                    String cellName = csvTitle[i];
                    if (cellName != null) {
                        if (!cellName.startsWith("@")) {
                            cellNameList.add(cellName);
                            columnIndexList.add(i);
                        }
                    }
                }
                
                
                getSql(tableName, cellNameList);
                System.out.println("  开始向表" + tableName + "导入数据...");
                doBeforeImport(tableName, disableConsStrSet, enableConsStrSet,
                        disableIndexesStrSet, enableIndexesStrSet);
                ps = conn.prepareStatement(sql);
                
                for (csvRow = csvReader.readNext(); csvRow != null; csvRow = csvReader.readNext()) {
                    count++;
                    int paramIndex = 1;
                    for(Integer i : columnIndexList){
                    	ps.setObject(paramIndex, getValue(csvRow[i], i));
                    	paramIndex++;
                    }
                    ps.addBatch();
                    if (count == 10) {
                        ps.executeBatch();
                        ps.clearBatch();
                        recordCount += count;
                        count = 0;
                        if (recordCount % 1000000 == 0) {
                            System.out.println("已插入" + recordCount + "条记录.");
                        }
                    }
                }
                ps.executeBatch();
                recordCount += count;
                doAfterImport(tableName, filename, sheetName);
                System.out.println("导入完成.记录数：" + recordCount);
                Date endTime = new Date();
                elapsedTime = endTime.getTime() - startTime.getTime();
            }
            importResult = new ImportResult(true, recordCount, elapsedTime);
        } catch (Exception e) {
            System.out.println("行：" + (recordCount + count));
            e.printStackTrace();
            importResult = new ImportResult(false);
        } finally {
            DbUtils.closeQuietly(ps);
            try {
                csvReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return importResult;
    }

}